package org.x.legalcasemod.service.Impl;

import cn.dev33.satoken.stp.StpUtil;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.x.commonmod.enums.AuditStatus;
import org.x.commonmod.enums.LegalStatus;
import org.x.legalcasemod.dto.OperatorCseDTO;
import org.x.legalcasemod.entity.CaseMaterialEntity;
import org.x.legalcasemod.entity.LegalCaseEntity;
import org.x.legalcasemod.mapper.CaseManagementMapper;
import org.x.legalcasemod.mapper.CaseMaterialMapper;
import org.x.legalcasemod.service.IApplyCaseService;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;

@Service
public class ApplyCaseServiceImpl extends ServiceImpl<CaseManagementMapper, LegalCaseEntity> implements IApplyCaseService {
/**
 * 案件操作@TODO
 * @param operatorCaseDTO
 */
@Autowired
  private  CaseMaterialMapper caseMaterialMapper;
@Autowired
private CaseManagementMapper caseManagementMapper;

    /**
     * 申请案件和保存草稿
     * @param operatorCaseDTO
     */
    @Override
    @Transactional
    public void operatorCase(OperatorCseDTO operatorCaseDTO) {
        //案件表
        LegalCaseEntity legalCaseEntity = new LegalCaseEntity();
        //材料表
        CaseMaterialEntity caseMaterialEntity = new CaseMaterialEntity();
        //生成案件编号
        String caseNo = UUID.randomUUID().toString();
        legalCaseEntity.setCaseNo(caseNo);
        if(operatorCaseDTO.getOperation().equals("SUBMIT")){
            //案件设置为待受理
            legalCaseEntity.setStatus(LegalStatus.PENDING);
            for(CaseMaterialEntity caseMaterialEntity1:operatorCaseDTO.getMaterials()){
                caseMaterialEntity1.setCaseNo(caseNo);
                caseMaterialEntity1.setAuditStatus(AuditStatus.DRAFT);
                //插入证据表
                caseMaterialMapper.insertSelective(caseMaterialEntity1);
            }
        }
        else{
            //材料设置为待审核
            caseMaterialEntity.setAuditStatus(AuditStatus.PENDING);
            //案件设置为审核中
            legalCaseEntity.setStatus(LegalStatus.REVIEWING);
            //设置提交时间（草稿不设置）
            legalCaseEntity.setApplyTime(new Date());
            //证据表中设置为待审核
            for(CaseMaterialEntity caseMaterialEntity1:operatorCaseDTO.getMaterials()){
                caseMaterialEntity1.setCaseNo(caseNo);
                caseMaterialEntity1.setAuditStatus(AuditStatus.PENDING);
                //插入证据表
                caseMaterialMapper.insertSelective(caseMaterialEntity1);
            }
        }
        //拿到登陆用户的id
        Long login = StpUtil.getLoginIdAsLong();
        legalCaseEntity.setUserId(login);
        //拷贝
        BeanUtils.copyProperties(operatorCaseDTO,legalCaseEntity);
        //操作案件表
        caseManagementMapper.insertSelective(legalCaseEntity);
    }


}

